package com.ado.bazinga.core.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ado.bazinga.core.annotation.AdminLoginToken;
import com.ado.bazinga.core.annotation.ApiDesc;
import com.ado.bazinga.core.annotation.UserLoginToken;
import com.ado.bazinga.core.common.http.HttpResult;
import com.ado.bazinga.core.common.params.dto.UserDto;
import com.ado.bazinga.core.common.params.dto.UserLoginBean;
import com.ado.bazinga.core.common.params.dto.UserParam;
import com.ado.bazinga.core.common.params.vo.UserVO;
import com.ado.bazinga.core.dal.entity.User;
import com.ado.bazinga.core.exception.BazingaException;
import com.ado.bazinga.core.service.UserService;
import com.ado.bazinga.core.utils.EncryptUtils;
import com.ado.bazinga.core.utils.JWTUtils;

/**
 *@author adonais
 *@date 2020年3月22日
 *@description UserController.java
 **/
@RestController
@RequestMapping(value = "/api/user")
public class UserController {
	
	@Autowired
	@Qualifier(value = "userService")
	private UserService userService ;
	
	@PostMapping(value = "/login")
	public HttpResult userLogin(@RequestBody UserLoginBean userLoginBean) {
		if (StringUtils.isEmpty(userLoginBean.getEmail())) {
			throw new BazingaException("登录失败,用户名为空") ;
		}
		if (StringUtils.isEmpty(userLoginBean.getPassword())) {
			throw new BazingaException("登录失败,密码为空");
		}
		User user = userService.findByEmail(userLoginBean.getEmail()) ;
		if (user == null) {
			return HttpResult.error("登录失败,用户不存在");
		} else {
			String pwd = EncryptUtils.decode(user.getPassword());
			if (!(pwd.equals(userLoginBean.getPassword()))) {
				throw new BazingaException("登录失败，密码错误") ;
			} else {
				String token = JWTUtils.getToken(user) ;
				UserVO userVO = new UserVO() ;
				userVO.setUser(user);
				userVO.setToken(token);
				return HttpResult.ok(userVO);
			}
		}
	}
	
	@ApiDesc(desc = "用户注册接口")
	@PostMapping(value = "/createUser")
	public HttpResult createUser(@RequestBody UserParam userParam) {
		if (StringUtils.isEmpty(userParam.getEmail())) {
			throw new BazingaException("注册失败,邮箱不能为空");
		}
		if (StringUtils.isEmpty(userParam.getPassword())) {
			throw new BazingaException("注册失败,密码不能为空");
		}
		User user = new User() ;
		user = assemblyUser(userParam) ;
		User authUser = userService.findByEmail(user.getEmail()) ;
		if (authUser != null ) {
			throw new BazingaException("用户邮箱已注册，不能重复注册");
		}
		user.setPassword(EncryptUtils.encode(user.getPassword()));
		boolean flag = userService.createUser(user);
		if (flag) {
			return HttpResult.ok("用户注册成功");
		}
		return HttpResult.error("用户注册失败") ;
	}
	
	@ApiDesc(desc = "用户修改信息接口")
	@UserLoginToken
	@AdminLoginToken
	@PostMapping(value = "/updateUser")
	public HttpResult updateUser(@RequestBody UserDto userDto) {
		if (StringUtils.isEmpty(userDto.getId().toString())) {
			throw new BazingaException("用户id不能为空");
		}
		User user = new User() ;
		user = assemblyDtoToEntity(user, userDto) ;
		User authUser = userService.findUserById(user.getId());
		if (authUser == null) {
			return HttpResult.error("用户不存在无法修改");
		}
		if (StringUtils.isNotEmpty(user.getPassword())) {
			user.setPassword(EncryptUtils.encode(user.getPassword()));
		}
		boolean flag = userService.updateUser(user) ;
		if (flag) {
			return HttpResult.ok("更新用户成功") ;
		}
		return HttpResult.error("更新用户失败");
	}
	
	@ApiDesc(desc = "按id删除用户")
	@AdminLoginToken
	@GetMapping(value = "deleteUserById")
	public HttpResult deleteUserById(String userId) {
		if (StringUtils.isEmpty(userId)) {
			throw new BazingaException("用户id不能为空");
		}
		boolean flag = userService.deleteUserById(Integer.valueOf(userId));
		if (flag) {
			return HttpResult.ok("删除用户成功");
		}
		return HttpResult.error("删除用户失败") ;
	}
	
	@ApiDesc(desc = "按id查询用户")
	@GetMapping(value = "getUserById")
	public HttpResult getUserById(String userId) {
		if (StringUtils.isEmpty(userId)) {
			throw new BazingaException("用户id不能为空") ;
		}
		User user = userService.findUserById(Integer.valueOf(userId)) ;
		if (user == null) {
			return HttpResult.error(421, "查无此用户");
		}
		return HttpResult.ok(user) ;
	}
	
	@ApiDesc(desc = "查询所有用户接口")
	@AdminLoginToken
	@GetMapping(value = "/getAllUsers")
	public HttpResult getAllUsers() {
		List<User> users = userService.getAllUsers() ;
		if (users.size() <= 0) {
			return HttpResult.error(421, "暂无用户信息");
		}
		return HttpResult.ok(users) ;
	}
	
	
	/**
	 * 组装User参数
	 * @param userLoginBean
	 * @return
	 */
	public User assemblyUser(UserParam userLoginBean) {
		User user = new User() ;
		try {
			BeanUtils.copyProperties(user, userLoginBean);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return user ;
	}
	
	/**
	 * dto 转实体
	 * @param userDto
	 * @return
	 */
	public User assemblyDtoToEntity(User user , UserDto userDto) {
		System.out.println(userDto.getAddress());
		user.setAddress(userDto.getAddress());
		user.setEmail(userDto.getEmail());
		user.setId(Integer.valueOf(userDto.getId()));
		user.setPassword(userDto.getPassword());
		user.setPhone(userDto.getPhone());
		user.setUsername(userDto.getUsername());
		return user ;
	}

}
